package com.by.medical.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.by.medical.bean.SysUser;
import com.by.medical.common.AxiosResult;
import com.by.medical.common.EnumStatus;
import com.by.medical.common.PageResult;
import com.by.medical.mapper.SysUserMapper;
import com.by.medical.util.MD5Util;
import com.by.medical.vo.SearchParamVO;
import com.by.medical.vo.SysUserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.UUID;



//@CrossOrigin//表示本类请求支持跨域
@RestController
@RequestMapping("/api/user/")
public class SysUserController {
    //controller调用mapper，mapper访问数据库
    private static final String UPLOAD_USER_DIR="D:\\mysystem\\thisaproject\\src\\main\\resources\\static\\upload\\user";
    private static final String UPDATA_USER_DIR="D:\\mysystem\\thisaproject\\src\\main\\resources\\static\\";
    @Autowired
    private SysUserMapper sysUserMapper;

    //修改密码
    public boolean updPass(int id,String newPass){
        int result=sysUserMapper.updatePass(id,newPass);
        return result>0;
    }
    //修改密码主方法
    @PostMapping("/pass")
    public AxiosResult<Object> updatePass(@RequestBody Map<Object,String> map){
        int id = Integer.parseInt(map.get("id"));
        String newPass = map.get("newPass");

        String encodeStr = MD5Util.encodeStr(newPass);

        if (updPass(id,encodeStr)) {
            return AxiosResult.success();
        }else {
            return AxiosResult.error();
        }
    }

    //导入----->将excel文件数据存储到数据库
    public boolean impUserBatch(List<SysUser> sysUserList){
        int result=sysUserMapper.insertUserBatch(sysUserList);
        return result>0;
    }
    @PostMapping("/import")
    public AxiosResult<Object> importUserInfo(MultipartFile importFile) throws Exception {
        //将页面提价的文件数据转成多个用户对象
//        System.out.println(importFile.getOriginalFilename());
//        System.out.println(importFile.getBytes().length);
//        System.out.println(importFile.getSize());
        //将文件里面的每一行内容转换SysUser对象
        //调用mapper接口  实现批量插入用户信息
        //前提：
        // 1.引入easypoi的依赖  2.SysUser的相关的属性使用@Excel修饰
        // 2.excel文件里面的列名不能随便写 必须与SysUser类中@Excel的name的值一致
        //importExcel(InputStream inputstream, Class<?> pojoClass,ImportParams params)
        //inputstream 文件内容

        //配置
        ImportParams importParams = new ImportParams();
        importParams.setStartSheetIndex(0);//指定读取第index+1个sheet
        importParams.setTitleRows(1);//标题
        importParams.setHeadRows(1);//头部 列

        List<SysUser> sysUserList = ExcelImportUtil.importExcel(importFile.getInputStream(), SysUser.class, importParams);
        //将流的内容转换成指定的类型对象
        //sysUserList.forEach(System.out::println);
        //批量新增
        sysUserList.forEach(sysUser -> sysUser.setPassword(MD5Util.encodeStr("123456")));
        sysUserList.forEach(sysUser -> sysUser.setDeptId(-1));
        sysUserList.forEach(sysUser -> sysUser.setJobId(-1));
        //sysUserList.forEach(System.out::println);
        boolean result=impUserBatch(sysUserList);
        if (result) {
            return AxiosResult.success();
        }else {
            return AxiosResult.error();
        }
    }

    //导出---->将用户信息导出到指定的文件中
    @PostMapping("/export")
    public void exportUserInfo(HttpServletResponse response) throws IOException {
        //获得导出的用户信息
        List<SysUser> sysUserList = sysUserMapper.queryAll();
        ExportParams params = new ExportParams();
        params.setTitle("用户列表信息");
        params.setSheetName("用户表 ");
        Workbook workbook = ExcelExportUtil.exportExcel(params, SysUser.class, sysUserList);

        //配置响应
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type","application/vnd.ms-excel");
        //服务器响应的不再是json数据，而是流文件(excel)文件
        String fileName = URLEncoder.encode("userInfo", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        workbook.write(response.getOutputStream());

        workbook.close();
    }

    //修改用户信息
    public boolean updUser(SysUser sysUser){
        int result=sysUserMapper.updateUser(sysUser);
        return result>0;
    }
    @PostMapping("/update")
    public AxiosResult<Object> updateUser(@RequestBody SysUser sysUser){
        //System.out.printf("前端数据"+sysUser);
        boolean result=updUser(sysUser);
        if (result){
            return AxiosResult.success();
        }else {
            return AxiosResult.error();
        }
     }

    //查询单个用户
    //http://127.0.0.1:9000/api/user/query/13
    @GetMapping("/query/{uid}")
    public  AxiosResult<SysUserVO> queryUserById(@PathVariable int uid){
        return AxiosResult.success(sysUserMapper.queryUserById(uid));
    }

    //新增用户
    public boolean insUser(SysUser sysUser){
        sysUser.setPassword(MD5Util.encodeStr(sysUser.getPassword()));
        int result=sysUserMapper.insertUser(sysUser);
        return result>0;
    }
    @PostMapping("/insert")
    public AxiosResult<Object> insertUser(@RequestBody SysUser sysUser){
        //System.out.printf("前端数据"+sysUser);
        boolean result=insUser(sysUser);
        if (result){
            return AxiosResult.success();
        }else {
            return AxiosResult.error();
        }
    }

    //查询用户信息，加用户部门名称+用户职位名称
    @GetMapping("/query")
    public AxiosResult<PageResult<SysUserVO>> queryUserDeptAndJob(SearchParamVO searchParamVO){
        if (searchParamVO.getNameParam() != "" || searchParamVO.getPhoneOrNumber()!="") {
            searchParamVO.setPage(1);
        }
        if (searchParamVO.getDeptId()!= -1 || searchParamVO.getJobId()!= -1) {
            searchParamVO.setPage(1);
        }
        int page = searchParamVO.getPage();
        int size = searchParamVO.getSize();

        PageHelper.startPage(page,size);

        List<SysUserVO> sysUserVOList=sysUserMapper.queryUserDeptAndJob(searchParamVO);
        PageInfo<SysUserVO> pageInfo=new PageInfo<>(sysUserVOList);

        PageResult<SysUserVO> pageResult=new PageResult<>();
        pageResult.setPage(page);
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setMaxPage(pageInfo.getPages());
        pageResult.setList(sysUserVOList);
        System.out.println(searchParamVO);
        return AxiosResult.success(pageResult);
    }

    //登录功能
    //开发接口
    //返回数据：status，msg，data
    //登录接口
    //{ status:"200",msg:"查询成功",data:userObj}
    //{ status:"500",msg:"查询失败"}
    //封装服务器返回的数据
    @GetMapping("/login")
    public AxiosResult<SysUser> userLogin(@RequestParam("phoneOrNo") String phoneOrNo,@RequestParam("pass") String pass){
        //Sting phoneOrNo,String pass 是前端提交的数据
        String encodeStr = MD5Util.encodeStr(pass);
        SysUser sysUser=sysUserMapper.userLogin(phoneOrNo,encodeStr);
        if (sysUser==null){
            return AxiosResult.error(EnumStatus.USER_LOGIN_ERROR);
        }else {
            return AxiosResult.success(sysUser);
        }
    }

    //查询所有用户信息
    @GetMapping("/all")
    public AxiosResult<List<SysUser>> queryAllUser(){
        return AxiosResult.success(sysUserMapper.queryAll());
    }

    //删除单个用户信息
    public boolean delUser(int id){
        int result=sysUserMapper.deleteUser(id);
        return result>0;
    }
    //删除单个用户
    @DeleteMapping("/delete/{uid}")
    public AxiosResult<Object> deleteUser(@PathVariable int uid){
        //return sysUserMapper.deleteUser(id);
        boolean result=delUser(uid);
        if (result){
            return AxiosResult.success();
        }else {
            return AxiosResult.error();
        }
    }

    //批量删除
    public boolean delBatch(List<Integer> idList){
        int result=sysUserMapper.deleteUserBatch(idList);
        return result>0;
    }
    @DeleteMapping ("/deleteBatch")
    public AxiosResult<Object> deleteUserBatch(@RequestParam("idList") List<Integer> idList){
        boolean result=delBatch(idList);
        if (result){
            return AxiosResult.success();
        }else {
            return AxiosResult.error();
        }
    }

    //上传用户头像
    @PostMapping("/upload")
    public AxiosResult<String> uploadUserImage(MultipartFile uploadFile){
        String originalFilename = uploadFile.getOriginalFilename();//获得文件名称及后缀
        //正常开发中:
        //1.存储外部服务器 (nginx)
        //2.云端服务器(OSS) 对象存储服务器

        //后端维护用户上传的图片(本地磁盘)
        //把用户每天上传的图片 存储到以日期为准一个目录中
        //弊端: 前端页面不能正常访问存储本地磁盘文件
        //解决: 需要添加映射处理
        String curDateStr = LocalDate.now().toString();
        File targetDir=new File(UPLOAD_USER_DIR,curDateStr);
        if(!targetDir.exists()){
            targetDir.mkdirs();
        }

        String extension = StringUtils.getFilenameExtension(originalFilename);
        String fileName = UUID.randomUUID().toString().replaceAll("-","");
        String targetFileName = fileName+"."+extension;

        try {
            uploadFile.transferTo(new File(targetDir,targetFileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //删除空白文件夹
        File oldFile =new File(UPLOAD_USER_DIR);
        File[] array = oldFile.listFiles();
        for (int i=0;i<array.length;i++) {
            File[] f2 = array[i].listFiles();
            if(!array[i].isFile()) {
                //if(f2==null) break;
                if (f2.length == 0) {
                    array[i].delete();
                }
            }
        }
        return AxiosResult.success("/upload/user/"+curDateStr+"/"+targetFileName);
    }

    //修改用户头像旧头像要删除
    @GetMapping("/deleteImage")
    public AxiosResult<String> deletePastImage(String userPastImage){
        File file = new File(UPDATA_USER_DIR,userPastImage);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
        }
        return AxiosResult.success();
    }
}